<?php

namespace MyBlog\Models;

use Illuminate\Database\Eloquent\Model;

class Gallery extends Model
{
    protected $guarded = array('id');
    
    public function imgs() {
    	return $this->hasMany('MyBlog\Models\GalleryImg')
    			->where('disabled', false);
    }
    
    public function comments() {
    	return $this->hasMany('MyBlog\Models\Comment', 'gallery_id');
    }
    
    public function category() {
    	return $this->belongsTo('MyBlog\Models\Category', 'category_id');
    }
    
    public function coverUrl($dimension = null){
    	$imgUrl = null;
    	$cover = GalleryImg::where('gallery_id', $this->id)
    			->where('is_cover', true)
    			->first();
    	if(is_null($cover)) {
    		$imgUrl = url('imgs/cover.jpg');	
    	}else {
    		$imgUrl = $cover->imgUrl($dimension);
    	}
    	return $imgUrl;
    }
    
    public function getUpdateTime() {
    	$newImg = $this->imgs()->orderBy('created_at', 'DESC')->first();
    	return $newImg->created_at->format('Y-m-d h:i'); 
    }
    
    
    public static $rules = [
    	'category_id' => 'required',
    	'name' => 'required',
    ];
    
    public static $msgs = [
    	'category_id.required' => '分类不能为空。',
    	'name.required' => '相册名不能为空。',
    ];
}
